package com.springcloud.play.novel.service.impl;

import com.springcloud.play.mapper.NovelChapterMapper;
import com.springcloud.play.mapper.NovelMapper;
import com.springcloud.play.novel.config.NovelCrawlerConfig;
import com.springcloud.play.novel.model.Novel;
import com.springcloud.play.novel.model.NovelChapter;
import com.springcloud.play.novel.service.NovelService;
import jakarta.annotation.PostConstruct;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class NovelServiceImpl implements NovelService {

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private NovelChapterMapper novelChapterMapper;

    @Autowired
    private NovelCrawlerConfig novelCrawlerConfig;

    private OkHttpClient client;

    @PostConstruct
    public void init() {
        client = new OkHttpClient.Builder()
                .connectTimeout(novelCrawlerConfig.getTimeout(), TimeUnit.MILLISECONDS)
                .readTimeout(novelCrawlerConfig.getTimeout(), TimeUnit.MILLISECONDS)
                .writeTimeout(novelCrawlerConfig.getTimeout(), TimeUnit.MILLISECONDS)
                .build();
    }

    @Override
    @Transactional
    public void crawlNovel(String novelUrl) {
        try {
            // 获取小说详情页面
            Document novelDoc = getDocument(novelUrl);

            // 解析小说信息
            Novel novel = new Novel();

            // 标题解析
            Element titleElement = novelDoc.selectFirst("div.info h1");
            if (titleElement == null) {
                throw new RuntimeException("未找到小说标题元素");
            }
            novel.setTitle(titleElement.text());

            // 作者解析
            Element authorElement = novelDoc.selectFirst("div.info p:nth-child(2)");
            if (authorElement != null) {
                novel.setAuthor(authorElement.text().replace("作者：", ""));
            } else {
                novel.setAuthor("未知作者");
            }

            // 分类解析
            Element categoryElement = novelDoc.selectFirst("div.info p:nth-child(3)");
            if (categoryElement != null) {
                novel.setCategory(categoryElement.text().replace("分类：", ""));
            } else {
                novel.setCategory("未知分类");
            }

            // 状态解析
            Element statusElement = novelDoc.selectFirst("div.info p:nth-child(4)");
            if (statusElement != null) {
                novel.setStatus(statusElement.text().replace("状态：", ""));
            } else {
                novel.setStatus("未知状态");
            }

            // 简介解析
            Element descElement = novelDoc.selectFirst("div.intro");
            if (descElement != null) {
                novel.setDescription(descElement.text());
            } else {
                novel.setDescription("暂无简介");
            }

            // 封面解析
            Element coverElement = novelDoc.selectFirst("div.cover img");
            if (coverElement != null) {
                novel.setCoverUrl(coverElement.attr("src"));
            }

            novel.setCreateTime(LocalDateTime.now());
            novel.setUpdateTime(LocalDateTime.now());
            novel.setChaptersCount(0);
            novel.setWordCount(0);

            // 检查是否已存在该小说
            Novel existingNovel = novelMapper.selectByTitle(novel.getTitle());
            if (existingNovel != null) {
                novel.setId(existingNovel.getId());
                novelMapper.update(novel);
            } else {
                novelMapper.insert(novel);
            }

            // 爬取章节列表
            String chaptersListUrl = novelUrl + "/chapters";
            crawlNovelChapters(novel.getId(), chaptersListUrl);

        } catch (Exception e) {
            throw new RuntimeException("爬取小说信息失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public void crawlNovelChapters(Long novelId, String chaptersListUrl) {
        try {
            // 获取章节列表页面
            Document chaptersDoc = getDocument(chaptersListUrl);

            // 获取最新章节数
            Integer maxChapterNumber = novelChapterMapper.selectMaxChapterNumberByNovelId(novelId);
            if (maxChapterNumber == null) {
                maxChapterNumber = 0;
            }

            // 解析章节列表
            Elements chapterElements = chaptersDoc.select("div.chapters a");
            int newChaptersCount = 0;
            int totalWordCount = 0;

            for (Element chapterElement : chapterElements) {
                String chapterTitle = chapterElement.text();
                String chapterUrl = novelCrawlerConfig.getBaseUrl() + chapterElement.attr("href");

                // 提取章节号
                Integer chapterNumber = extractChapterNumber(chapterTitle);
                if (chapterNumber == null) {
                    continue;
                }

                // 只爬取新章节
                if (chapterNumber > maxChapterNumber) {
                    // 爬取章节内容
                    NovelChapter chapter = new NovelChapter();
                    chapter.setNovelId(novelId);
                    chapter.setTitle(chapterTitle);
                    chapter.setChapterNumber(chapterNumber);
                    chapter.setSourceUrl(chapterUrl);
                    chapter.setCreateTime(LocalDateTime.now());
                    chapter.setUpdateTime(LocalDateTime.now());

                    // 获取章节内容
                    Document chapterDoc = getDocument(chapterUrl);
                    Element contentElement = chapterDoc.selectFirst("div.content");
                    if (contentElement != null) {
                        String content = contentElement.text();
                        chapter.setContent(content);
                        chapter.setWordCount(content.length());
                        totalWordCount += content.length();
                    }

                    novelChapterMapper.insert(chapter);
                    newChaptersCount++;
                }
            }

            // 更新小说信息
            if (newChaptersCount > 0) {
                Novel novel = novelMapper.selectById(novelId);
                if (novel != null) {
                    novel.setChaptersCount(novel.getChaptersCount() + newChaptersCount);
                    novel.setWordCount(novel.getWordCount() + totalWordCount);
                    novel.setUpdateTime(LocalDateTime.now());
                    novelMapper.update(novel);
                }
            }

        } catch (Exception e) {
            throw new RuntimeException("爬取小说章节失败: " + e.getMessage(), e);
        }
    }

    @Override
    public Novel getNovelById(Long novelId) {
        return novelMapper.selectById(novelId);
    }

    @Override
    public List<NovelChapter> getNovelChapters(Long novelId) {
        return novelChapterMapper.selectByNovelId(novelId);
    }

    @Override
    public NovelChapter getNovelChapter(Long chapterId) {
        return novelChapterMapper.selectById(chapterId);
    }

    @Override
    public void scheduledCrawl() {
        // 获取所有小说
        List<Novel> novels = novelMapper.selectList();

        // 遍历所有小说，爬取更新
        for (Novel novel : novels) {
            try {
                String novelUrl = novelCrawlerConfig.getBaseUrl() + "/novel/" + novel.getId();
                crawlNovelChapters(novel.getId(), novelUrl + "/chapters");
            } catch (Exception e) {
                // 记录错误日志，但继续爬取下一本小说
                System.err.println("爬取小说更新失败: " + novel.getTitle() + ", 错误: " + e.getMessage());
            }
        }
    }

    @Override
    public List<Novel> searchNovels(String keyword) {
        // 这里应该实现搜索功能，但目前简化处理
        List<Novel> novels = novelMapper.selectList();
        List<Novel> result = new ArrayList<>();

        for (Novel novel : novels) {
            if (novel.getTitle().contains(keyword) || novel.getAuthor().contains(keyword) || novel.getDescription().contains(keyword)) {
                result.add(novel);
            }
        }

        return result;
    }

    // 辅助方法：获取网页文档
    private Document getDocument(String url) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected response code: " + response);
            }

            String html = response.body().string();
            return Jsoup.parse(html);
        }
    }

    // 辅助方法：从章节标题中提取章节号
    private Integer extractChapterNumber(String chapterTitle) {
        // 简单提取章节号，实际项目中可能需要更复杂的逻辑
        try {
            // 尝试从标题中提取数字
            String numberStr = chapterTitle.replaceAll("[^0-9]", "");
            if (!numberStr.isEmpty()) {
                return Integer.parseInt(numberStr);
            }
        } catch (NumberFormatException e) {
            // 忽略解析错误
        }
        return null;
    }
}